<?php if (!defined('TL_ROOT')) die('You can not access this file directly!');


/**
 * This class is for online shop order process - payment.
 * params order step
 * This is the children of controller.
 * PHP5 CMS Typolight
 * Copyright is 34n.sam@gmail.com
 */
 
 /**
 * Start page
 */
session_start();

$profile = new ProfileDetail();
$profile->run();

class ProfileDetail extends Controller
{	
	/**
	 * This is class construct function.
	 * @params null
	 * @Return null
	 */
	public function __construct()
	{
		parent::__construct();		
	}
	
	/** 
	 * Start page function
	 * @params null
	 * @Return null
	 */
	public function run()
	{
		if (FE_USER_LOGGED_IN)
		{
			$this->import('FrontendUser', 'User');
			$this->loadDataContainer('tl_member');			
			$this->import('Database');
			
			if (!$this->User->id)
				return;
			
			if (isset($_POST) && $_POST)
				$is_modified = $this->saveProfileDetail($this->User->id);
			else
				$is_modified = false;
				
			echo $this->displayProfileDetail($this->User->id, $is_modified);
		}
		else
		{
			$this->redirect("sign-in.html");
		}
	}
	
	/**
	 * Save the member profile information
	 * @params string
	 * @Return string
	 */
	private function saveProfileDetail($id_member=0)
	{
		if (!$id_member)
			return false;
		
		$password = "";
		$strSocial = "";
		$strSocial = implode(',', $_POST['social']);
		$objEmail = $this->Database->prepare("SELECT COUNT(`id`) AS cnt FROM `tl_member` WHERE `email`=? AND `id`!=?")
									->execute($_POST['email'], $id_member, time(), time());
		$cnt_email = intval($objEmail->cnt);
									
		if ($cnt_email <= 0)
		{
			if (isset($_POST['password']) && $_POST['password'])
			{	
				
					$password = trim($_POST['password']);
					$password_2 = substr(md5(uniqid('', true)), 0, 23);
					$password_1 = sha1($password_2 . $password);
					$password = "$password_1:$password_2";			
					
					$objMember = $this->Database->prepare("UPDATE tl_member SET firstname=?, lastname=?, gender=?, social=?, state=?, cur=?, city=?, email=?, password=?, dateOfBirth=?, mobile=? WHERE id=?")
									->execute($_POST['firstname'], $_POST['lastname'], $_POST['gender'], $strSocial, $_POST['province'], $_POST['cur'], $_POST['city'], $_POST['email'], $password, strtotime($_POST['birthday']), trim($_POST['mobile']), $id_member);				
				
			}
			else
			{
				$objMember = $this->Database->prepare("UPDATE tl_member SET firstname=?, lastname=?, gender=?, social=?, state=?, cur=?, city=?, email=?, dateOfBirth=?, mobile=? WHERE id=?")
								->execute($_POST['firstname'], $_POST['lastname'], $_POST['gender'], $strSocial, $_POST['province'], $_POST['cur'], $_POST['city'], $_POST['email'], strtotime($_POST['birthday']), trim($_POST['mobile']), $id_member);
			}
		}
		else
		{
			return false;
		}

		return true;
	}
	
	/**
	 * Generate the profile detail page
	 * @params string
	 * @Return string
	 */
	private function displayProfileDetail($id_member=0, $is_modified=false)
	{
		if (!$id_member)
			return;
		
		$this->loadLanguageFile('countries');
		include(TL_ROOT . '/system/config/countries.php');
		
		$objMember = $this->Database->prepare("SELECT * FROM tl_member WHERE id=?")
									->execute($id_member);
		if ($objMember->numRows < 1)
			return;
			
		// Get the states.
		$arrStates = array();
		$objStates = $this->Database->prepare("SELECT * FROM `china_province` ORDER BY `province_en`")
									->execute(time());
		
		while ($objStates->next())
		{
			$arrStates[$objStates->id] = $objStates->province_en;
		}
		
		// Get State.
		$arrCitys = array();			
		$objCitys = $this->Database->prepare("SELECT * FROM `china_city` WHERE pid=? ORDER BY `city_en`")
									->execute($objMember->state);
									
		while ($objCitys->next())
		{
			$arrCitys[$objCitys->id] = $objCitys->city_en;
		}
		
		$obj_currency = $this->Database->prepare("SELECT * FROM `tl_currency`")
										->execute(time());
		$arr_currency = array();
		while($obj_currency->next()){
			$arr_currency[$obj_currency->iso_code] = $obj_currency->iso_code;
		}
		$select_currency = '<select name="cur">';
		foreach ($arr_currency as $key=>$currency){
			$select_currency .= '<option value="'.$key.'"'.(($objMember->cur==$key)?' selected="selected"':'').'>'.$currency.'</option>';
		}
		$select_currency .= "</select>";
		
		/*if (!$is_modified)
			$strHtml = "";
		else
			$strHtml ="<div class=\"notice\">The change has been saved.</div>";*/
			
		$strHtml = "<div class=\"path\"><a title=\"HOME\" href=\"index.php\">HOME</a>&nbsp;" . htmlentities('>') . "&nbsp;<a title=\"MY ACCOUNT\" href=\"profile.html\">" . (($this->User->firstname) ? $this->User->firstname : $this->User->email) . "'s account</a></div><div class=\"quick_tool\">
					<a title=\"ORDER STATUS\" href=\"order-status.html\">ORDER STATUS</a> <a href=\"profile_detail.html\" title=\"PROFILE\" class=\"active\">PROFILE</a> <a title=\"WISHLIST\" href=\"backpocket.html\">WISHLIST</a> <a title=\"ADDRESS BOOK\" href=\"shipping_payment.html\">ADDRESS BOOK</a>
				</div>
		<div class=\"main\" id=\"signin\">
		<div class=\"main_left\">
		<script type=\"text/javascript\">
	jQuery(function(){

			// Date Picker
			jQuery('#datepicker').datepicker({
				changeMonth: true,
				changeYear: true,
				yearRange: '1970:2010'
			});

			// Change Province
			jQuery(\"select[@name=province]\").change(function() {
				jQuery.ajax({
					type: \"POST\",
					url: \"getCity.php\",
					data: \"province=\"+(jQuery(\"select[@name=province]\").val()),
					success: function(msg){
						jQuery(\"select[@name=city]\").html(msg);
					}
				});
			});

			// validate signup form on keyup and submit
		jQuery(\"#signupForm\").validate({
			rules: {
				firstname: \"required\",
				lastname: \"required\",
				email: {
					required: true,
					email: true
				},
				password: {
					minlength: 5
				},
				confirm_password: {
					minlength: 5,
					equalTo: \"#password\"
				},
				mobile: {
					required: true,
					digits: true
				}
			},
			messages: {
				firstname: \"Please input your first name\",
				lastname: \"Please input your last name\",
				email: \"Please enter a valid email address\",
				password: {
					minlength: \"Your password must be at least 5 characters.\"
				},
				confirm_password: {
					minlength: \"Your password must be at least 5 characters.\",
					equalTo: \"Please make sure to enter the same password.\"
				},
				mobile: \"Please enter  a valid mobile number.\"
			}
		});	
	});
		
		</script> " . ((!$is_modified) ? (($_POST['email']) ? "<div class=\"error\">Another customer is already using this email. Please choose another.</div>" : "") : "<div class=\"notice\">* The change has been saved.</div>") . "
	<form id=\"signupForm\" action=\"profile_detail.html\" name=\"form\" method=\"post\">
	<div class=\"reg_account\">
		<label style=\"display: none;\" id=\"msg_1\"><span style=\"color: green; font-weight: bold;\">Your account have been created, and please sign in your account on right side.</span></label>
		<p>
			<label>First Name</label><input type=\"text\" name=\"firstname\" value=\"" . $objMember->firstname . "\" class=\"ce_text\" />
		</p>
		<p>
			<label>Last Name</label><input type=\"text\" name=\"lastname\" value=\"" . $objMember->lastname . "\" class=\"ce_text\" />
		</p>
		<p>
			<label>Email</label><input type=\"text\" id=\"email\" name=\"email\" value=\"" . $objMember->email . "\" class=\"ce_text\" />
			<label id=\"error_0\" class=\"error\" for=\"email\" generated=\"true\" style=\"display:none\">The email address is exist.</label>
		</p>
		<p>
			<label>Password</label><input type=\"password\" id=\"password\" name=\"password\" value=\"\" class=\"ce_text\" />
		</p>
		<p>
			<label>Confirm Password</label><input type=\"password\" id=\"confirm_password\" name=\"confirm_password\" value=\"\" class=\"ce_text\" />
		</p>
		<p>
			<label>Mobile</label><input type=\"text\" id=\"mobile\" name=\"mobile\" value=\"" .$objMember->mobile. "\" class=\"ce_text\" />
		</p>
	</div> <!-- reg_account end -->
	<div class=\"optional\">
		<h4>Tell us more about you... (optional)</h4>
		<p>
			<span class=\"gender\"><strong>Gender</strong> <input type=\"radio\" name=\"gender\" value=\"male\" class=\"checkbox\"" . (($objMember->gender == 'male') ? " checked=\"checked\"" : "") . " />M <input type=\"radio\" name=\"gender\" value=\"female\" class=\"checkbox\"" . (($objMember->gender == 'female') ? " checked=\"checked\"" : "") . " />F</span>
			<span class=\"birthday\">
				<strong>Birthday</strong>
				<input type=\"text\" name=\"birthday\" id=\"datepicker\" value=\"" . date('m/d/Y', $objMember->dateOfBirth ) . "\" />
			</span>
			<span class=\"currency\">Choose your preferred currency ".$select_currency."</span>
		</p>
		<h5>In which city do you spend most of your time other than where you live?</h5>
		<p>
			<select class=\"most_time\" name=\"province\">
				<option value=\"\">Please select province</option>";
			foreach ($arrStates as $key=>$strStatesInfo)
			{
				if ($key == $objMember->state)
					$strHtml .= "<option value=\"".$key."\" selected=\"selected\">".$strStatesInfo."</option>";
				else
					$strHtml .= "<option value=\"".$key."\">".$strStatesInfo."</option>";
			}
			$strHtml .= "</select>
			<select class=\"some_time\" name=\"city\">
				<option value=\"\">Please select city</option>";
			foreach ($arrCitys as $key=>$strCity)
			{
				if ($key == $objMember->city)
					$strHtml .= '<option value="'.$key.'"  selected="selected">'.$strCity.'</option>';
				else
					$strHtml .= '<option value="'.$key.'">'.$strCity.'</option>';
			}
			
			$arrSocial = explode(',', $objMember->social);
			$arrnewsletter = unserialize($objMember->newsletter);
			$is_newsletter = $arrnewsletter[0];
			
			$strHtml .= "</select>
		</p>
		<h5>Your social networks</h5>
		<p class=\"social\">
			<label><input type=\"checkbox\" name=\"social[]\" value=\"Facebook\" class=\"checkbox\" " . (in_array('Facebook', $arrSocial) ? 'checked="checked" ' : '') . "/>Facebook</label>
			<label><input type=\"checkbox\" name=\"social[]\" value=\"My Space\" class=\"checkbox\" " . (in_array('My Space', $arrSocial) ? 'checked="checked" ' : '') . "/>My Space</label>
			<label><input type=\"checkbox\" name=\"social[]\" value=\"LinkedIN\" class=\"checkbox\" " . (in_array('LinkedIN', $arrSocial) ? 'checked="checked" ' : '') . "/>LinkedIN</label>
			<label><input type=\"checkbox\" name=\"social[]\" value=\"Foursquare\" class=\"checkbox\" " . (in_array('Foursquare', $arrSocial) ? 'checked="checked" ' : '') . "/>Foursquare</label>
			<label><input type=\"checkbox\" name=\"social[]\" value=\"Twitter\" class=\"checkbox\" " . (in_array('Twitter', $arrSocial) ? 'checked="checked" ' : '') . "/>Twitter</label>
			<label><input type=\"checkbox\" name=\"social[]\" value=\"Flickr\" class=\"checkbox\" " . (in_array('Flickr', $arrSocial) ? 'checked="checked" ' : '') . "/>Flickr</label>
			<label><input type=\"checkbox\" name=\"social[]\" value=\"Youtube\" class=\"checkbox\" " . (in_array('Youtube', $arrSocial) ? 'checked="checked" ' : '') . "/>Youtube</label>
			<label><input type=\"checkbox\" name=\"social[]\" value=\"City Weekend\" class=\"checkbox\" " . (in_array('City Weekend', $arrSocial) ? 'checked="checked" ' : '') . "/>City Weekend</label>
		</p>
	</div> <!-- optional end -->
	<!--<div class=\"protocol\">
		<p><input type=\"checkbox\" name=\"term\" value=\"1\" " . (($is_newsletter) ? 'checked="checked"' : '') . "/>I agree with terms of use.</p>
		<p><input type=\"checkbox\" name=\"newsletter\" value=\"1\" />Yes, send me emails showcasing new items and gift ideas.</p>
	</div>-->
	<p class=\"submits\"><input type=\"submit\" name=\"submit\" value=\"UPDATE PROFILE\" class=\"submit\" /></p>
</form></div></div>";
	
		return $strHtml;
	}
}
?>